package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constants.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    RemoteCartService remoteCartService;

    @Autowired
    RemoteProductService remoteProductService;

    @Autowired
    RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitService rabbitService;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    @Override
    public TradeVo orderTradeData() {
        //1.获取当前登录用户id
        Long userId = SecurityContextHolder.getUserId();
        //2.远程调用购物车微服务，获取打钩商品列表 List<CartInfo>
        R<List<CartInfo>> cartInfoCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL == cartInfoCheckedListResult.getCode()) {
            throw new ServiceException(cartInfoCheckedListResult.getMsg());
        }
        List<CartInfo> cartInfoList = cartInfoCheckedListResult.getData();
        if (CollectionUtils.isEmpty(cartInfoList)) {
            throw new ServiceException("数据不合法");
        }
        //3.类型转换： List<CartInfo> -> List<OrderItem>
        List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setThumbImg(cartInfo.getThumbImg());
            orderItem.setSkuPrice(cartInfo.getSkuPrice());
            //orderItem.setSkuPrice(cartInfo.getCartPrice()); // cartPrice应该含优惠卷之后价格。
            orderItem.setSkuNum(cartInfo.getSkuNum()); //修改OrderItem类 skuNum属性类型： Long -> Integer
            return orderItem;
        }).toList();

        //4.计算总价格
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            BigDecimal sum = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()));
            totalAmount = totalAmount.add(sum);
        }

        String tradeNo = generateTradeNo(userId);

        TradeVo tradeVo = new TradeVo();
        //数据封装
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }


    @Transactional
    /**
     * 下订单业务逻辑：
     * 1.验证用户重复提交表单
     * 2.验证表单参数是否空
     * 3.校验价格变化
     * 4.校验库存锁定库存
     * 5.保存订单（订单表、订单项表、订单日志表）
     * 6.删除购物车选中商品
     * 7.发送延迟消息,取消订单
     */
    @Override
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        //下订单业务逻辑：
        //1.验证用户重复提交表单
        /*  这个校验和删除不是原子的，所以，不能使用。
        //1.1校验用户提交表单tradeNo交易流水号是否有效。判断是否为重复表单提交。
        Boolean flag = this.checkTradeNo(userId,orderForm.getTradeNo());
        if(!flag){ // flag=false  1） 5分钟过期    2) 处理第一次提交后删除了
            throw new ServiceException("请勿重复提交表单");
        }
        //1.2 首次提交表单处理请求，流水号判断合法后，立即删除redis中流水号。
        deleteTradeNo(userId);
        */
        //1.3 采用Lua脚本保证校验和删除具有原子性。
        String scriptText = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "\treturn redis.call('del',KEYS[1])\n" +
                "else\n" +
                "\treturn 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<Long>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        String userTradeKey = "user:tradeNo:" + userId;
        Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo());
        if (result == 0) {
            throw new ServiceException("请勿重复提交表单");
        }

        //2.验证表单参数是否空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("参数数据不合法");
        }


        //3.校验价格变化
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()) {
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();
        Map<Long, BigDecimal> skuIdToSkuPriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        String priceResult = "";
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuIdToSkuPriceMap.get(orderItem.getSkuId())) != 0) {
                priceResult += orderItem.getSkuName() + "价格变了;";
            }
        }
        if (StringUtils.hasText(priceResult)) {
            //更新购物车价格
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            throw new ServiceException(priceResult);
        }

        //4.校验库存锁定库存 TODO   远程还需要去重？ 需要，因为远程调用涉及重试问题。OpenFeign重试，以及负载均衡重试问题。
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();

        R<String> checkAndLockResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == checkAndLockResult.getCode()) {
            throw new ServiceException(checkAndLockResult.getMsg());
        }
        String checkAndLockStr = checkAndLockResult.getData();
        if (StringUtils.hasText(checkAndLockStr)) {
            throw new ServiceException(checkAndLockStr);
        }

        //5.保存订单（订单表、订单项表、订单日志表）
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            //e.printStackTrace();
            throw new ServiceException("下单失败"); //下单失败，需要发异步消息解除库存。 TODO
        }

        //6.删除购物车选中商品
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);

        //7.发送延迟消息,取消订单
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId),
                MqConst.CANCEL_ORDER_DELAY_TIME); // 1分钟不支付，就取消订单

        return orderId;
    }

    /**
     * 5.保存订单（订单表、订单项表、订单日志表）
     *
     * @param orderForm 订单表单
     * @return 订单主键
     */
    private Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String username = SecurityContextHolder.getUserName();

        //1.保存订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(username);
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); //实付总金额   含优惠券和运费在内。
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount); // 商品总价格，不含优惠券和运费等。
        orderInfo.setFeightFee(orderForm.getFeightFee()); //运费
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0); //订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderInfo.setRemark(orderForm.getRemark());
        orderInfoMapper.insert(orderInfo); //主键回填

        //2.保存订单项
        orderItemList = orderForm.getOrderItemList();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //3.表单订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setOperateUser("用户"); // 操作人：用户；系统；后台管理员
        orderLog.setProcessStatus(0);
        orderLog.setNote("下单成功");
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }

    private void deleteTradeNo(Long userId) {
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }

    //校验流水号
    private Boolean checkTradeNo(Long userId, String tradeNoForm) {
        String userTradeKey = "user:tradeNo:" + userId;
        String userTradeNo = (String) redisTemplate.opsForValue().get(userTradeKey);
        return tradeNoForm.equals(userTradeNo);
    }


    @Override
    public TradeVo buy(Long skuId) {
        //1.获取当前登录用户id
        Long userId = SecurityContextHolder.getUserId();
        //2.远程调用商品服务，根据skuId查询ProductSku
        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()) {
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSku productSku = productSkuResult.getData();
        //3.类型转换： ProductSku -> OrderItem

        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(productSku.getId());
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        //orderItem.setSkuPrice(cartInfo.getCartPrice()); // cartPrice应该含优惠卷之后价格。
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);


        //4.计算总价格
        BigDecimal totalAmount = productSku.getSalePrice();
        //5.生成交易流水号：订单好
        String tradeNo = generateTradeNo(userId);

        //6.封装数据结果
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }


    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityContextHolder.getUserId();
        List<OrderInfo> orderInfoList = orderInfoMapper.selectUserOrderInfoList(userId, orderStatus);
        if (CollectionUtils.isEmpty(orderInfoList)) {
            return new ArrayList<>();
        }

        //思路一：迭代每个订单，通过订单id到订单表查询这个订单的订单项集合，封装在订单对象的orderItemList属性上就可以了。 不推荐。效率低，发很多次数据库查询sql
        //思路二：得到所有订单id集合，用 in 操作做where。一次性将每个订单的订单项合并在一起返回。 推荐。只需要发送1次SQL
        List<Long> orderIdList = orderInfoList.stream().map(orderInfo -> orderInfo.getId()).toList();
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIdList));
        Map<Long, List<OrderItem>> oderIdToOrderItemListMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));

        for (OrderInfo orderInfo : orderInfoList) {
            orderInfo.setOrderItemList(oderIdToOrderItemListMap.get(orderInfo.getId()));
        }

        //给每一个订单封装订单项属性
        return orderInfoList;
    }

    @Transactional
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) { //订单已经存在，但是未支付
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.QUEUE_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) { //订单已经存在，但是未支付
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);
        }
    }


    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo,orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }
}